const { sequelize, testConnection } = require('../config/database');
const { Weather, WeatherForecast, Geocode, Poi, Route, News } = require('../models');

// 天气数据
const weatherData = [
  {
    city: '广州市',
    province: '广东省',
    adcode: '440100',
    weather: '晴',
    temperature: '26',
    winddirection: '东南风',
    windpower: '3',
    humidity: '65',
    reporttime: new Date()
  },
  {
    city: '深圳市',
    province: '广东省',
    adcode: '440300',
    weather: '多云',
    temperature: '28',
    winddirection: '东风',
    windpower: '2',
    humidity: '70',
    reporttime: new Date()
  },
  {
    city: '北京市',
    province: '北京市',
    adcode: '110100',
    weather: '阴',
    temperature: '22',
    winddirection: '北风',
    windpower: '4',
    humidity: '55',
    reporttime: new Date()
  },
  {
    city: '上海市',
    province: '上海市',
    adcode: '310100',
    weather: '小雨',
    temperature: '24',
    winddirection: '东风',
    windpower: '3',
    humidity: '80',
    reporttime: new Date()
  }
];

// 天气预报数据
const forecastData = [
  {
    city: '广州市',
    date: new Date(),
    week: '1',
    dayweather: '晴',
    nightweather: '多云',
    daytemp: '28',
    nighttemp: '22',
    daywind: '东南风',
    nightwind: '东南风',
    daypower: '3',
    nightpower: '3'
  },
  {
    city: '广州市',
    date: new Date(Date.now() + 86400000),
    week: '2',
    dayweather: '多云',
    nightweather: '小雨',
    daytemp: '26',
    nighttemp: '20',
    daywind: '东风',
    nightwind: '东风',
    daypower: '2',
    nightpower: '2'
  },
  {
    city: '广州市',
    date: new Date(Date.now() + 172800000),
    week: '3',
    dayweather: '小雨',
    nightweather: '阴',
    daytemp: '24',
    nighttemp: '18',
    daywind: '北风',
    nightwind: '北风',
    daypower: '4',
    nightpower: '4'
  }
];

// 地理编码数据
const geocodeData = [
  {
    address: '广州市天河区珠江新城',
    location: '113.289405,23.013125',
    type: 'geo',
    province: '广东省',
    city: '广州市',
    district: '天河区',
    street: '珠江新城',
    formatted_address: '广东省广州市天河区珠江新城',
    adcode: '440106',
    level: 'POI'
  },
  {
    address: '深圳市南山区科技园',
    location: '113.953537,22.543099',
    type: 'geo',
    province: '广东省',
    city: '深圳市',
    district: '南山区',
    street: '科技园',
    formatted_address: '广东省深圳市南山区科技园',
    adcode: '440305',
    level: 'POI'
  }
];

// POI数据
const poiData = [
  {
    name: '广州塔',
    type: '旅游景点',
    location: '113.289405,23.013125',
    address: '广东省广州市海珠区阅江西路222号',
    distance: 500,
    tel: '020-89338222',
    website: 'http://www.cantontower.com',
    email: 'info@cantontower.com',
    pcode: '440000',
    citycode: '020',
    adcode: '440105',
    business_area: '珠江新城',
    rating: 4.5,
    photos: JSON.stringify(['https://example.com/photo1.jpg', 'https://example.com/photo2.jpg'])
  },
  {
    name: '深圳湾公园',
    type: '公园',
    location: '113.953537,22.543099',
    address: '广东省深圳市南山区深圳湾',
    distance: 1000,
    tel: '0755-12345678',
    website: 'http://www.szwanpark.com',
    email: 'info@szwanpark.com',
    pcode: '440000',
    citycode: '0755',
    adcode: '440305',
    business_area: '深圳湾',
    rating: 4.8,
    photos: JSON.stringify(['https://example.com/photo3.jpg', 'https://example.com/photo4.jpg'])
  }
];

// 路线规划数据
const routeData = [
  {
    origin: '广州市天河区珠江新城',
    destination: '广州市海珠区广州塔',
    strategy: 0,
    waypoints: JSON.stringify(['广州市越秀区北京路']),
    distance: 8500,
    duration: 1800,
    tolls: 0.00,
    toll_distance: 0,
    steps: JSON.stringify([
      {
        instruction: '从珠江新城出发',
        distance: 2000,
        duration: 400
      },
      {
        instruction: '沿珠江路行驶',
        distance: 3000,
        duration: 600
      },
      {
        instruction: '到达广州塔',
        distance: 3500,
        duration: 800
      }
    ]),
    polyline: JSON.stringify([
      [113.289405, 23.013125],
      [113.285000, 23.015000],
      [113.280000, 23.018000]
    ]),
    traffic_condition: '畅通'
  }
];

// 检查数据是否存在
const checkDataExists = async () => {
  try {
    const weatherCount = await Weather.count();
    const forecastCount = await WeatherForecast.count();
    const geocodeCount = await Geocode.count();
    const poiCount = await Poi.count();
    const routeCount = await Route.count();
    const newsCount = await News.count();
    
    return {
      weather: weatherCount > 0,
      forecast: forecastCount > 0,
      geocode: geocodeCount > 0,
      poi: poiCount > 0,
      route: routeCount > 0,
      news: newsCount > 0
    };
  } catch (error) {
    console.error('检查数据存在性失败:', error.message);
    return {
      weather: false,
      forecast: false,
      geocode: false,
      poi: false,
      route: false,
      news: false
    };
  }
};

// 自动填充数据
const autoSeedData = async () => {
  console.log('🌱 检查并自动填充数据...');
  
  try {
    // 检查数据库连接
    const isConnected = await testConnection();
    if (!isConnected) {
      console.error('❌ 数据库连接失败，无法填充数据');
      return false;
    }
    
    // 检查现有数据
    const existingData = await checkDataExists();
    
    let filledCount = 0;
    
    // 填充天气数据
    if (!existingData.weather) {
      console.log('🌤️  填充天气数据...');
      await Weather.bulkCreate(weatherData);
      filledCount++;
    } else {
      console.log('✅ 天气数据已存在，跳过填充');
    }
    
    // 填充天气预报数据
    if (!existingData.forecast) {
      console.log('📅 填充天气预报数据...');
      await WeatherForecast.bulkCreate(forecastData);
      filledCount++;
    } else {
      console.log('✅ 天气预报数据已存在，跳过填充');
    }
    
    // 填充地理编码数据
    if (!existingData.geocode) {
      console.log('🗺️  填充地理编码数据...');
      await Geocode.bulkCreate(geocodeData);
      filledCount++;
    } else {
      console.log('✅ 地理编码数据已存在，跳过填充');
    }
    
    // 填充POI数据
    if (!existingData.poi) {
      console.log('📍 填充POI数据...');
      await Poi.bulkCreate(poiData);
      filledCount++;
    } else {
      console.log('✅ POI数据已存在，跳过填充');
    }
    
    // 填充路线规划数据
    if (!existingData.route) {
      console.log('🛣️  填充路线规划数据...');
      await Route.bulkCreate(routeData);
      filledCount++;
    } else {
      console.log('✅ 路线规划数据已存在，跳过填充');
    }
    
    // 填充新闻数据
    if (!existingData.news) {
      console.log('📰 填充新闻数据...');
      const { seedNewsData } = require('./seed-news');
      await seedNewsData();
      filledCount++;
    } else {
      console.log('✅ 新闻数据已存在，跳过填充');
    }
    
    if (filledCount > 0) {
      console.log(`✅ 自动数据填充完成，填充了 ${filledCount} 个表的数据`);
    } else {
      console.log('✅ 所有数据已存在，无需填充');
    }
    
    return true;
  } catch (error) {
    console.error('❌ 自动数据填充失败:', error.message);
    return false;
  }
};

// 如果直接运行此脚本
if (require.main === module) {
  autoSeedData().then(() => {
    process.exit(0);
  }).catch((error) => {
    console.error('脚本执行失败:', error);
    process.exit(1);
  });
}

module.exports = autoSeedData; 